<template>
  <div class="text-editor">
    <div class="editor-container">
      <div class="image-wrapper" @click="handleImageClick" ref="containerRef">
        <img :src="selectedImage" class="editor-image" ref="imageRef" @load="initImage">
        <!-- 输入框和预览文字的容器 -->
        <div v-if="isEditing" class="text-input-container" :style="{
          left: editPosition.x + 'px',
          top: editPosition.y + 'px',
          width: inputSize.width + 'px',
          height: inputSize.height + 'px'
        }">
          <input ref="textInputRef" v-model="textContent" type="text" class="floating-input" :style="{
            fontSize: `${currentFontSize}px`,
            color: textColor,
          }" @blur="handleBlur" @keyup.enter="saveText" @input="adjustInputSize">
          <!-- 添加四个角的调整点 -->
          <div class="resize-handle top-left" @mousedown.stop="startResize('top-left', $event)"></div>
          <div class="resize-handle top-right" @mousedown.stop="startResize('top-right', $event)"></div>
          <div class="resize-handle bottom-left" @mousedown.stop="startResize('bottom-left', $event)"></div>
          <div class="resize-handle bottom-right" @mousedown.stop="startResize('bottom-right', $event)"></div>
        </div>
      </div>
    </div>

    <!-- 编辑文案 -->
    <div class="text-toolbar">
      <div class="input-group">
        <el-input 
          v-model="videoTitle" 
          :rows="1" 
          placeholder="请输入文案" 
          maxlength="100" 
          show-word-limit 
        />
        <el-select 
          v-model="videoType" 
          placeholder="请选择视频类型"
          size="default"
          class="video-type-select"
        >
          <el-option
            v-for="item in videoTypes"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
            <span class="video-type-item">
              <el-icon class="video-type-icon">
                <component :is="item.icon" />
              </el-icon>
              {{ item.label }}
            </span>
          </el-option>
        </el-select>
        <el-button size="default" @click="clearText">
          清空
        </el-button>
      </div>
    </div>

    <!-- 文字工具栏 -->
    <div class="text-toolbar">
      <div class="tool-group">
        <span>字号：</span>
        <el-select v-model="fontSize" size="small" style="width: 100px">
          <el-option v-for="size in [12, 14, 16, 18, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64, 68, 72, 76, 80]"
            :key="size" :label="`${size}px`" :value="size">
          </el-option>
        </el-select>
      </div>
      <div class="tool-group">
        <span>颜色：</span>
        <el-color-picker v-model="textColor" size="small"></el-color-picker>
      </div>
      <!-- 进度条 -->
      <div class="progress">
        <div class="wrapper">
          <div :style="{ width: progressPercent + '%' }" class="inner" ref="inner">
            <span>{{ progressPercent }}%</span>
          </div>
        </div>
      </div>
      <el-button class="btn" @click="handleUpload" :disabled="btnText === '完成'">{{ btnText }}</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useEditPos } from '../hooks/useEditPos'
import { 
  VideoPlay, // 普通
  Headset,   // 音乐
  Monitor,   // 游戏
  Food,      // 美食
  Location,  // 旅游
  Collection,// 知识
  Calendar   // 日常
} from '@element-plus/icons-vue'

const props = defineProps({
  selectedImage: {
    type: String,
    default: ''
  },
  btnText: {
    type: String,
    default: '上传'
  },
  progressPercent: {
    type: Number,
    default: 0
  }
})

const selectedImage = ref(props.selectedImage)
const imageRef = ref(null)
const containerRef = ref(null)
const textInputRef = ref(null)
const fontSize = ref(20)
const textColor = ref('#000000')
const zoom = ref(1)

const { textContent, isEditing, isResizing, startResize, editPosition, initialFontSize, currentFontSize, inputSize, baseWidth, adjustInputSize, handleImageClick } = useEditPos(textInputRef, imageRef)

// 保存文字到图片
const saveText = async () => {
  if (!textContent.value.trim()) {
    isEditing.value = false
    return
  }

  try {
    const result = await drawTextOnImage({
      image: imageRef.value,
      text: textContent.value,
      position: editPosition.value,
      fontSize: fontSize.value,
      color: textColor.value,
      inputPaddingLeft: 4
    })

    selectedImage.value = result
  } catch (error) {
    console.error('Failed to save text:', error)
  }

  isEditing.value = false
  textContent.value = ''
}

// 绘制文字到图片的核心函数
const drawTextOnImage = async ({
  image,
  text,
  position,
  fontSize,
  color,
  inputPaddingLeft = 0
}) => {
  return new Promise((resolve) => {
    const img = new Image()
    img.onload = () => {
      // 创建与原图相同尺寸的画布
      const canvas = document.createElement('canvas')
      canvas.width = img.naturalWidth
      canvas.height = img.naturalHeight

      const ctx = canvas.getContext('2d')
      ctx.drawImage(img, 0, 0)

      // 设置文字样式
      ctx.font = `${currentFontSize.value / zoom.value}px Arial`
      ctx.fillStyle = color
      ctx.textBaseline = 'middle'

      // 绘制文字
      const x = (position.x + inputPaddingLeft) / zoom.value
      const y = (position.y) / zoom.value

      ctx.fillText(text, x, y)

      resolve(canvas.toDataURL('image/png'))
    }

    img.src = image.src
  })
}

// 初始化图片位置
const initImage = () => {
  const iw = imageRef.value.naturalWidth  // 图片宽度
  const ih = imageRef.value.naturalHeight // 图片高度
  const { width: containerWidth, height: containerHeight } = containerRef.value.getBoundingClientRect()

  const imgAspectRatio = iw / ih // 图片的宽高比
  const containerAspectRatio = containerWidth / containerHeight // 容器的宽高比

  let newWidth, newHeight

  if (imgAspectRatio > containerAspectRatio) {
    // 图片宽高比大于容器宽高比，以容器宽度为基准
    newWidth = containerWidth
    newHeight = containerWidth / imgAspectRatio
  } else {
    // 图片宽高比小于等于容器宽高比，以容器高度为基准
    newHeight = containerHeight
    newWidth = containerHeight * imgAspectRatio
  }

  // 计算缩放倍数
  zoom.value = newWidth / iw

  // 对图片和容器进行重置
  imageRef.value.style.width = newWidth + 'px'
  imageRef.value.style.height = newHeight + 'px'
}

const handleBlur = () => {
  // 只有在没有调整大小时才保存文字
  if (!isResizing.value) {
    saveText()
  }
}

// 监听文本内容变化
watch(textContent, () => {
  adjustInputSize()
})

// 修改 fontSize 的监听
watch(fontSize, (newSize) => {
  initialFontSize.value = newSize
  currentFontSize.value = newSize
  baseWidth.value = inputSize.value.width
  adjustInputSize()
})

// 文案编辑
const videoTitle = ref('')
const videoType = ref(1)
const videoTypes = [
  { value: 1, label: '普通', icon: VideoPlay },
  { value: 2, label: '音乐', icon: Headset },
  { value: 3, label: '游戏', icon: Monitor },
  { value: 4, label: '美食', icon: Food },
  { value: 5, label: '旅游', icon: Location },
  { value: 6, label: '知识', icon: Collection },
  { value: 7, label: '日常', icon: Calendar }
]

const clearText = () => {
  videoTitle.value = ''
  videoType.value = 1
}

// 上传按钮
const emit = defineEmits(['uploadVideo'])

const handleUpload = () => {
  emit('uploadVideo', {
    coverImg: selectedImage.value,
    videoTitle: videoTitle.value,
    videoType: videoType.value
  })
}

</script>

<style lang="scss" scoped>
.text-editor {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  .editor-container {
    flex: 1;
    position: relative;
    overflow: hidden;
  }

  .image-wrapper {
    height: 100%;
    position: relative;
    max-height: 100%;
  }

  .text-input-container {
    position: absolute;
    transform: translate(0, -50%);
    z-index: 10;

    .resize-handle {
      position: absolute;
      width: 8px;
      height: 8px;
      background: #1890ff;
      border-radius: 50%;

      &.top-left {
        top: -4px;
        left: -4px;
        cursor: nw-resize;
      }

      &.top-right {
        top: -4px;
        right: -4px;
        cursor: ne-resize;
      }

      &.bottom-left {
        bottom: -4px;
        left: -4px;
        cursor: sw-resize;
      }

      &.bottom-right {
        bottom: -4px;
        right: -4px;
        cursor: se-resize;
      }
    }
  }

  .floating-input {
    width: 100%;
    height: 100%;
    background: transparent;
    border: 1px solid #1890ff;
    outline: none;
    padding: 0 4px;
    margin: 0;
    box-sizing: border-box;

    &:focus {
      background: rgba(255, 255, 255, 0.9);
    }
  }

  .text-toolbar {
    margin-top: 20px;
    padding: 15px;
    background: #f5f5f5;
    border-radius: 8px;
    display: flex;
    gap: 20px;
    align-items: center;
    flex-shrink: 0;

    .tool-group {
      display: flex;
      align-items: center;
      gap: 10px;

      span {
        white-space: nowrap;
      }
    }

    .input-group {
      display: flex;
      gap: 10px;
      align-items: center;
      width: 100%;

      .el-input {
        flex: 1;
      }

      .video-type-select {
        width: 120px;
      }
    }
  }
}

/* 进度条 */
.progress {
  width: 100%;
  height: 60px;
  background: #ccc;
  border-radius: 20px;
  display: flex;
  align-items: center;
  padding: 0 20px;
}

.progress .wrapper {
  position: relative;
  width: 100%;
  height: 5px;
}

.progress .wrapper::before {
  content: '';
  width: 100%;
  background: #eee;
  height: 5px;
  border-radius: 3px;
  display: block;
}

.inner {
  position: absolute;
  width: 0%;
  background: #7ebf50;
  height: 5px;
  transition: 0.1s;
  border-radius: 3px;
  left: 0;
  top: 0;
}

.inner span {
  position: absolute;
  right: 0;
  top: 10px;
  transform: translateX(50%);
  font-size: 12px;
  background: #333;
  color: #fff;
  padding: 0 3px;
}

.inner span::before {
  content: '';
  position: absolute;
  border: 5px solid #333;
  left: 50%;
  top: 0;
  transform: translate(-50%, -100%);
  border-left-color: transparent;
  border-top-color: transparent;
  border-right-color: transparent;
}

:deep(.video-type-item) {
  display: flex;
  align-items: center;
  gap: 5px;

  .video-type-icon {
    font-size: 16px;
  }
}
</style>
